// pages/userInfoCenter/index.js
const App = getApp();
const { Dialog } = require("../../../../../config/modal")
const utils = require("../../../../../utils/util")
Page({
    /**
     * 页面的初始数据
     */
    data: {
        theamTextColor: App.globalData.theamTextColor,
        address: {
            showArea: false,
            list: [],
            region: [],
            area: "",
            item: {
                name: "",
                phone: "",
                province: "",
                city: "",
                district: "",
                address: "",
                isDefault: true
            }
        },
        rules:
        {
            name: {
                msg: "请填写收货人",
                required: true,
            },
            phone: { val: "", msg: "请填写联系电话", required: true },
            province: { val: "", msg: "请选择地区", required: true },
            address: { val: "", msg: "请填写详细地址", required: true },
        }
    },
    URL: {
        save: "/address/add",
        update: "/address/update",
        region: "/address/getAreaList"
    },
    page: {},
    /** 获取来这一页的页路径 */
    getFromPagePath() {
        var pages = getCurrentPages();
        let prePage = pages[pages.length - 2];  //上一个页面
        return "/" + prePage.route;
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.hideShareMenu();
        if (!utils.isInvalid(options.item)) {
            let item = JSON.parse(options.item);
            let province = item.province;
            let cityName = item.city;
            let area = item.district;
            this.setData({
                'address.item': item,
                'address.area': province + ' ' + cityName + ' ' + area,
            })
        } else {
            let user = App.$getUserInfo();
            this.setData({
                'address.item.phone': user.userPhone,
                'address.item.name': user.realName,
                'address.item.address': utils.isInvalid(user.schoolName)?'':user.schoolName,
            })
        }
        utils.saveUrlParams(this, options, ['item'])
        utils.saveFromPage(App, getCurrentPages());
    },
    onShow() {
        this.getRegion()
    },
    getRegion() {
        let region = App.$getData("region");
        if (utils.isInvalid(region)) {
            App.$get(true, this.URL.region, {}, res => {
                if (res.R) {
                    // 页面初始值
                    let region = res.data;
                    App.$saveData("region", region);
                    this.setAddress(region)
                }
            })
            return;
        }
        this.setAddress(region)
    },
    onSelectAddress() {
        this.setData({
            'address.showArea': true
        })
    },
    onCancelChange() {
        this.setData({
            'address.showArea': false
        })
    },
    onAreaConfirm(event) {
        const { picker, value, index } = event.detail;
        let province = value[0].name + "省";
        let cityName = value[1].name + "市";
        let area = value[2];
        this.setData({
            'address.item.province': province,
            'address.item.city': cityName,
            'address.item.district': area,
            'address.area': province + ' ' + cityName + ' ' + area,
        })
        this.onCancelChange();
    },

    onAreaChange(event) {
        const { picker, value, index } = event.detail;
        // value[0] 就是第一列 value[1] 就是第二列 value[2] 就是第三列值 index就是当前滚动的列的索引
        let oneIndex = picker.getColumnIndex(index);
        if (index == 0) {
            let data = this.data.address.region[oneIndex]['city'];
            picker.setColumnValues(index + 1, data)
            picker.setColumnValues(index + 2, this.data.address.region[oneIndex]['city'][0]['area'])
        } else if (index == 1) {
            picker.setColumnValues(index + 1, this.data.address.region[oneIndex]['city'][0]['area'])
        }
    },
    setAddress() {
        let region = App.$getData("region");
        let addressList = [
            {
                values: region,
                className: "column"
            },
            {
                values: region[0]['city'],
                className: "column1"
            },
            {
                values: region[0]['city'][0]['area'],
                className: "column2"
            }
        ]
        this.setData({
            'address.list': addressList,
            'address.region': region,
        })
    },


    // 提交地址信息
    submitInfo() {
        let addressInfo = this.data.address.item;
        let rules = this.data.rules;
        let errors = 0;
        for (const key in addressInfo) {
            if (Object.hasOwnProperty.call(addressInfo, key)) {
                const val = addressInfo[key];
                if (!utils.isInvalid(rules[key]) && rules[key].required && utils.isInvalid(val)) {
                    let ruleKey = 'rules.' + key + '.val'
                    this.setData({
                        [ruleKey]: rules[key].msg
                    })
                    ++errors;
                }
            }
        }
        if (errors > 0) {
            return;
        }

        if (utils.isInvalid(this.data.address.item.id)) {
            this.save();
            return;
        }
        this.update();
    },

    save() {
        App.$post(true, this.URL.save, this.data.address.item, res => {
            this.reqResult(res);
        })
    },
    update() {
        App.$post(true, this.URL.update, this.data.address.item, res => {
            this.reqResult(res);
        })
    },
    reqResult(res) {
        if (res.R) {
            Dialog.alert({
                message: '信息已保存',
                width: "250px",
                confirmButtonColor: "#D2691E",
                confirmButtonText: "确定",
            }).then(() => {
                this.goBack();
            })
        }
    },
    onFieldChange(e) {
        let name = e.currentTarget.dataset.name;
        let dateField = "address.item." + name;
        let rulesField = "rules." + name + '.val';
        console.log(dateField)
        console.log(rulesField)
        this.setData({
            [dateField]: e.detail,
            [rulesField]: utils.isInvalid(e.detail) ? this.data.rules[name].msg : ''
        })
    },

    goBack() {
        let params = utils.getFromUrlParams(this);
        App.$redirectTo(this.getFromPagePath() + params, false)
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
